module AppiumRspecSetup
  class SetupIos
    def self.setup_ios!
      AppiumRspecSetup::Gemfile.configure_gemfile_and_bundle!
      AppiumRspecSetup::Rspec.initialize_rspec

      puts 'What is the name of the app?'
      app_name = gets.chomp

      File.open('app_config.yml', 'w') do |file|
        file.write(%Q{
rspec:
  app_name: #{app_name}
  device_name: 'iPhone 6'
  version_number: '8.4'
})
      end

      file_array = File.readlines('spec/spec_helper.rb')

      insert_hash = {
          'appium_lib' => "require 'appium_lib'",
          'pry' => "require 'pry'",
          'yaml' => "require 'yaml'\n"
      }

      offset = 0

      insert_hash.each do |substring_key, line_for_file_value|
        file_array.insert(offset, line_for_file_value) unless file_array.any? do |line|
          line.include? substring_key
        end
      end

      unless file_array.any? {|line| line.include? '::APP_CONFIG' }
        file_array.insert(-2, %Q{
  ::APP_CONFIG = YAML.load(File.read("./app_config.yml"))
  ::APP_NAME = APP_CONFIG['rspec']['app_name']
  ::BUILD_FOLDER = Dir["\#{ENV['HOME']}/Library/Developer/Xcode/DerivedData/*"].select{|path|path.include? APP_NAME}.first
  ::APP_PATH =  Dir["\#{BUILD_FOLDER}/**/\#{APP_NAME}.app"].first
  ::DEVICE_NAME = APP_CONFIG['rspec']['device_name']
  ::VERSION_NUMBER = APP_CONFIG['rspec']['version_number']
}
        )
      end

      unless file_array.any? {|line| line.include? 'def desired_caps' }
        file_array.insert(-2, %Q{
  def desired_caps
    {
      caps: {
        platformName: 'iOS',
        deviceName:  DEVICE_NAME,
        versionNumber:  VERSION_NUMBER,
        app: APP_PATH
      },
      appium_lib: {
        sauce_username: nil, # don't run on sauce
        sauce_access_key: nil,
        wait: 10,
      }
    }
  end
}
        )
      end

      File.open('spec/spec_helper.rb', 'w') do |file|
        file.puts file_array
      end
    end
  end
end